package com.education.common.core;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.education.common.pojo.AjaxResult;
import com.education.common.utils.StringUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * web层通用数据处理
 *
 * @author ruoyi
 */
public class BaseController {
//	  protected HttpServletRequest request;
//	  protected HttpServletResponse response;
//	  protected HttpSession session;

    /**
     * 将前台传递过来的日期格式的字符串，自动转化为Date类型
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    /**
     * 设置请求分页数据
     */
    protected void startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = pageDomain.getOrderBy();
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }

    /**
     * 响应请求分页数据
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    protected TableDataInfo getDataTable(List<?> list) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(200);
        rspData.setRows(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }

    /**
     * 响应请求数据
     */
    protected String getList(Object object) {
        JSONObject obj = new JSONObject();
        obj.put("code", 200);
        obj.put("info", "响应成功");
        obj.put("data", object);
        return obj.toString();
    }

    //返回结果json格式
    public final static void writeJSON(Object obj, HttpServletResponse response, String code, String message) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        JSONObject dataJson = new JSONObject();
        dataJson.put("code", code);
        dataJson.put("message", message);
        dataJson.put("returnObject", obj);
        PrintWriter out = response.getWriter();
        out.print(dataJson.toString());
        out.flush();
        out.close();
    }

    //返回结果json格式
    public final static void writeJSON(Object obj, HttpServletResponse response, String code, String message,String data) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        JSONObject dataJson = new JSONObject();
        dataJson.put("code", code);
        dataJson.put("message", message);
        dataJson.put("data", obj);
        PrintWriter out = response.getWriter();
        out.print(dataJson.toString());
        out.flush();
        out.close();
    }
    //返回结果json格式
    public final static void writeJSON(Object obj, HttpServletResponse response, String code, String message,int size) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        JSONObject dataJson = new JSONObject();
        dataJson.put("code", code);
        dataJson.put("message", message);
        dataJson.put("data", obj);
        dataJson.put("size", size);
        PrintWriter out = response.getWriter();
        out.print(dataJson.toString());
        out.flush();
        out.close();
    }

    /**
     * 响应返回结果
     *
     * @param rows 影响行数
     * @return 操作结果
     */
    protected AjaxResult toAjax(int rows) {
        return rows > 0 ? success() : error();
    }

    /**
     * 返回成功
     */
    public AjaxResult success() {
        return AjaxResult.success();
    }

    /**
     * 返回失败消息
     */
    public AjaxResult error() {
        return AjaxResult.error();
    }

    /**
     * 返回成功消息
     */
    public AjaxResult success(String message) {
        return AjaxResult.success(message);
    }

    /**
     * 返回失败消息
     */
    public AjaxResult error(String message) {
        return AjaxResult.error(message);
    }

    /**
     * 返回错误码消息
     */
    public AjaxResult error(int code, String message) {
        return AjaxResult.error(code, message);
    }

    /**
     * 页面跳转
     */
    public String redirect(String url) {
        return StringUtils.format("redirect:{}", url);
    }

//    public SysUser getUser() {
//        return ShiroUtils.getUser();
//    }
//
//    public void setUser(SysUser user) {
//        ShiroUtils.setUser(user);
//    }
//
//    public Long getUserId() {
//        return getUser().getUserId();
//    }
//
//    public String getLoginName() {
//        return getUser().getLoginName();
//    }

    /**
     * 时间戳+六位随机数生成主键
     *
     * @return 生成的唯一字符编码
     */
    public String generatingprimarykey() {

        //生成时间戳
        Long simple = System.currentTimeMillis();
        //六位随机数,为变量赋随机值100000-999999;
        int random = new Random().nextInt(999999) + 100000;
        // 返回生成的字符串
        return simple.toString() + random;

    }

    /**
     * 当前时间
     *
     * @return 当前时间
     */
    public Timestamp getNowTime() {
        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //将java.util.Date转换为java.sql.Timestamp
        Timestamp date = Timestamp.valueOf(df.format(new Date()));
        return date;
    }
//    /**
//	   * 注入request与response
//	 * @throws Exception 
//	   * */
//	  @SuppressWarnings("static-access")
//	  @ModelAttribute
//	  public void setReqAndRes(HttpServletRequest request,
//	      HttpServletResponse response) throws Exception {
//	    this.request = request;
//	    this.response = response;
//	    this.session = request.getSession();
//	    String token = (String)request.getSession().getAttribute("token");
//		SysAppLogin user = (SysAppLogin)request.getSession().getAttribute("user");
//		if (token==null || token.equals("") || user == null || user.equals("")){
//            /*return "ERROR";*/
//            this.writeJSON("请前往登陆",response,"201","false");
//        }
//	   
//	  }
}
